"""
过滤器
"""
from django.db.models import Q
from django_filters import rest_framework as filters

from .models import Goods


class GoodsFilter(filters.FilterSet):
    """
    商品过滤类
    """
    min_price = filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
    max_price = filters.NumberFilter(field_name="shop_price", lookup_expr='lte')

    top_category = filters.NumberFilter(method="top_category_filter")

    # 模糊查询 icontains忽略大小写 contains不忽略大小写
    # name = filters.CharFilter(field_name="name", lookup_expr='icontains')

    # queryset, name, value 这三个参数必须加
    def top_category_filter(self, queryset, name, value):
        return queryset.filter(Q(category_id=value)|Q(category__parent_category_id=value)|Q(category__parent_category_id__parent_category=value))

    class Meta:
        model = Goods
        fields = ['min_price', 'max_price']
